$(function(){
    getClientList();

    $('#side-menu ul').eq(1).addClass('in');

    $('#btn_search').on('click',function(){
        $("#pageNum").val(1);
        getClientList();
    });

    $(document).keydown(function(event){
        if(event.keyCode==13){
            $("#btn_search").click();
        }
    });

    //弹出modal
    $('#add_client_update').on('click',function () {
        //清空数据
        $('input[name=versionName]').val('');
        $('input[name=versionCode]').val('');
        $('input[name=packageAddress]').val('');
        $('#platformType').val(1);
        $('#userType').val(1);
        $('#updateMessage').val('');
        $('#addClientModal').modal('show');
        $('#myModalLabel').text('新增版本');
    })

    //提交
    $('#btn_add_client').on('click',function () {

        var validFlag = $('#add_client_form').valid();
        if (validFlag) {
            addClientUpdate();
            $('#addClientModal').modal('hide');
        }else{
            return false;
        }
    });


    /**
     *  功能描述：添加用户验证
     */

    $('#add_client_form').validate({
        errorElement:'span',
        errorClass:'error',
        focusInvalid:false,
        ignore:'',
        rules:{
            versionName:{
                required:true
            },
            versionCode: {
                required: true
            }
        },
        messages:{

            versionName:{
                required:'请输入版本名称'
            },
            versionCode:{
                required:'请输入版本号'
            }
        },
        invalidHandler:function(event,validator){
            $('.alert-success').hide();
            $('.alert-error').show();
        },
        highlight:function(element){
            $(element).closest('.help-inline').removeClass('ok');
            $(element).closest('.form-group').removeClass('success').addClass('error');
        },
        unhighlight:function(element){
            $(element).closest('.form-group').removeClass('error');
        },
        success:function(label){
            label.addClass('valid').addClass('help-inline ok').closest('.form-group').removeClass('error').addClass('success');
        },
        submitHandler:function(form){
            $('.alert-success').show();
            $('.alert-error').hide();
        }
    });
});



/**
 *  功能描述：获取版本信息列表
 *  请求方式：GET
 *  请求地址：/api/update/list
 *  函数名称：getClientList
 */

function getClientList(){
    $.ajax({
        url: whole_path+'/api/client/list',
        type: 'GET',
        dataType: 'json',
        cache:false,
        data: $('#client_list_form').serialize(),
        beforeSend:function(data){
            $.progressBar({message:'<p>正在努力加载数据...</p>',modal:true,canCancel:true});
        },
        success:function(data){
            if(data.status == 0) {
                var json = data.data;
                var list = json.result;
                var temp = "";
                var operation = '';
                if (list != null && list.length>0){
                    $.each(list, function (index, item) {

                        var updateMessage = '';
                        if(item.updateMessage != null){
                            updateMessage = item.updateMessage.toString();
                            if (updateMessage.length > 20 && updateMessage != 0){
                                updateMessage = updateMessage.substring(0,20)+"...";
                            }else {
                                updateMessage
                            }
                        }

                        var platformType = item.platformType;
                        switch (platformType){
                            case 1:
                                platformType = 'Android'
                                break;
                            case 2:
                                platformType = 'PC'
                                break;
                        }

                        var user_type = item.userType;
                        switch (user_type){
                            case 1:
                                user_type = '车主版'
                                break;
                            case 2:
                                user_type = '专线版'
                                break;
                        }

                        operation = ' <a class="btn-sm btn-info btn-rounded" onclick="getClientDetail('+item.id+')">编辑</a> ';

                        temp += '<tr>'
                            + '<td data-title="版本名称">' + item.versionName + '</td>'
                            + '<td data-title="版本号">' + item.versionCode + '</td>'
                            + '<td data-title="更新描述" style="color:#0b94ea;max-width:200px;white-space:nowrap; overflow:hidden; text-overflow:ellipsis" data-container="body" data-toggle="popover" data-trigger="hover" data-placement="top" data-content="'+item.updateMessage+'">' + updateMessage + '</td>'
                            + '<td data-title="平台类型">' + platformType + '</td>'
                            + '<td data-title="用户类型">' + user_type + '</td>'
                            + '<td data-title="创建时间">' + timestampFormat(item.createTime) + '</td>'
                            + '<td data-title="操作">' + operation + '</td>'
                            + '</tr>';
                    })
                    $('#client_update_list tbody').html(temp);
                    $("[data-toggle='popover']").popover();
                    page('#pagination', json.pagecount, json.pageindex, json.pagesize, getClientList, '#pageNum');

                }else{
                    $.toast("没有查到数据",3000);
                    $('#client_update_list tbody').html('');
                    if($('#pagination').html().length > 0){
                        $('#pagination').jqPaginator('destroy');
                    }
                }
            }
        },
        complete:function(){
            $.progressBar().close();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            $.toast('服务器未响应,请稍候重试',5000);
        }
    })
}

/**
 *  功能描述：提交
 *  请求方式：POST
 *  请求地址：/api/update/editor
 *  函数名称：addClientUpdate
 */

function addClientUpdate(){
    $.ajax({
        url:whole_path+ '/api/client/editor',
        type: 'POST',
        dataType: 'json',
        data: $('#add_client_form').serialize(),
        beforeSend:function(){
            $.progressBar({message:'<p>正在努力加载数据...</p>',modal:false,canCancel:true});
        },
        success:function(data){
            if(data.status == 0){
                $.toast('操作成功',3000);
                getClientList();
            }else{
                $.toast(data.msg,3000);
            }

        },
        complete:function(){
            $.progressBar().close();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            $.toast('服务器未响应,请稍候重试',5000);
        }
    })

}


function getClientDetail(id) {
    $('#addClientModal').modal('show');
    $.ajax({
        url:whole_path+ '/api/client/detail',
        type: 'GET',
        dataType: 'json',
        data: {id:id},
        beforeSend:function(){
            $.progressBar({message:'<p>正在努力加载数据...</p>',modal:false,canCancel:true});
        },
        success:function(data){
            if(data.status == 0){
                $('#myModalLabel').text('修改版本');
                var json = data.data;
                $('input[name=id]').val(json.id);
                $('#platformType').val(json.platformType).selected;
                $('#userType').val(json.userType).selected;
                $('input[name=versionName]').val(json.versionName);
                $('input[name=versionCode]').val(json.versionCode);
                $('input[name=packageAddress]').val(json.packageAddress);
                $('#updateMessage').val(json.updateMessage);
            }else{
                $.toast(data.msg,3000);
            }

        },
        complete:function(){
            $.progressBar().close();
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
            $.toast('服务器未响应,请稍候重试',5000);
        }
    })
}


/**
 * 文件上传
 */
$(function () {
    $("#file").uploadify({
        'swf': '../../static/js/uploadify/uploadify.swf',
        'uploader': whole_path+'/api/client/upload',
        'fileObjName': 'file',
        'multi': false,
        'buttonText': '上传文件',
        'onUploadSuccess': function (file, data, response) {
            var json = JSON.parse(data);
            var input = $('input[name="packageAddress"]');
            input.val(json.fileInfo.path);
        },
        'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
            $('#progress').html(totalBytesUploaded + ' bytes uploaded of ' + totalBytesTotal + ' bytes.');
        },
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
        }
    });
})